//
//  ViewController.m
//  服务端
//
//  Created by 袁飞霞 on 16/5/17.
//  Copyright © 2016年 cn.sophietobeabetterone. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"

@interface ViewController()<GCDAsyncSocketDelegate>
@property (weak) IBOutlet NSTextField *textField;
@property (nonatomic, strong)  GCDAsyncSocket * clientSocket;
@property (nonatomic, strong) GCDAsyncSocket *serverSocket;
@property (nonatomic, strong) NSMutableArray *clients;
@end
@implementation ViewController
- (IBAction)start:(id)sender {
    
    [self.serverSocket acceptOnPort:self.textField.integerValue error:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];


}


-(NSMutableArray *)clients

{
    if (_clients == nil) {
        _clients = [[NSMutableArray alloc] init];
    }
    return _clients;
}


-(GCDAsyncSocket *)serverSocket
{
    if (_serverSocket == nil) {
        _serverSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        
    }
    return _serverSocket;
}


#pragma mark -----GCDAsyncSocketDelegate-----
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{

    [self.clients addObject:newSocket];
    
    [newSocket readDataWithTimeout:-1 tag:0];
    
    [newSocket writeData:[@"i am ios client" dataUsingEncoding:NSUTF8StringEncoding]withTimeout:-1 tag:0];
    
    
}

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@", str);
    
    [sock readDataWithTimeout:-1 tag:0];
    
    //如果不是当前的socket 就转发
    
    for (GCDAsyncSocket  * socket in self.clients) {
        if (socket != sock) {
            [socket writeData:data withTimeout:-1 tag:0];
            
        }
        
    }
    
}


@end
